<!--入库单-->
<template>
  <div class="inbound-order-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
        <button class="btn-new" @click="onAdd">新建</button>
        <div class="filters">
            <div class="filter-item">
                <label>关键词</label>
                <input type="text" placeholder="请输入产品名称或编号" v-model="query.keyword">
            </div>
            <div class="filter-item">
                <label>产品类型</label>
                <select v-model="query.receiptType">
                    <option value="">全部</option>
                    <option :value="0">生产入库</option>
                    <option :value="1">采购入库</option>
                    <option :value="2">销售退货</option>
                    <option :value="3">生产退料</option>
                    <option :value="4">委外入库</option>
                    <option :value="5">其他入库</option>
                </select>
            </div>
        </div>
        <div class="actions">
            <button class="btn-primary" @click="onSearch">搜索</button>
            <button class="btn-secondary" @click="onReset">重置</button>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>入库单号</th>
            <th>入库状态</th>
            <th>入库时间</th>
            <th>入库类型</th>
            <th>入库产品数</th>
            <th>入库仓库</th>
            <th>入库数量</th>
            <th>入库人</th>
            <th>库存金额</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="11" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-for="(item, index) in orders" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style">{{ item.receiptNo || item.receipt_no || '-' }}</td>
            <td><span :class="statusClass(statusLabel(item.receiptStatus))">{{ statusLabel(item.receiptStatus) }}</span></td>
            <td>{{ item.receiptTime || item.receipt_time || '-' }}</td>
            <td>{{ typeLabel(item.receiptType) }}</td>
            <td>{{ item.productCount ?? item.product_count ?? '-' }}</td>
            <td>{{ warehouseName(item.warehouseId) }}</td>
            <td>{{ item.quantity ?? '-' }}</td>
            <td>{{ personName(item.uId) }}</td>
            <td>{{ formatPrice(item.stock) }}</td>
            <td>{{ item.remark || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="onPageChange(query.pageNum - 1)">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: query.pageNum === page }" @click="onPageChange(page)">{{ page }}</button>
        <button @click="onPageChange(query.pageNum + 1)">&gt;</button>
        <select v-model="query.pageSize" @change="onPageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
      <!-- 新建入库单弹窗 -->
      <el-dialog v-model="addVisible" title="新建入库单" width="600px">
        <div class="form-grid">
          <div class="form-item">
            <div class="label">入库类型</div>
            <div class="field">
              <el-select v-model.number="addForm.receiptType" placeholder="请选择">
                <el-option :value="0" label="生产入库" />
                <el-option :value="1" label="采购入库" />
                <el-option :value="2" label="销售退货" />
                <el-option :value="3" label="生产退料" />
                <el-option :value="4" label="委外入库" />
                <el-option :value="5" label="其他入库" />
              </el-select>
            </div>
          </div>
          <div class="form-item">
            <div class="label">产品</div>
            <div class="field">
              <el-select v-model.number="addForm.productId" filterable placeholder="请选择产品" @visible-change="v=>v&&loadProductOptions()">
                <el-option v-for="p in productOptions" :key="p.id" :label="p.name" :value="p.id" />
              </el-select>
            </div>
          </div>
          <div class="form-item">
            <div class="label">数量</div>
            <div class="field"><el-input v-model.number="addForm.quantity" placeholder="请输入数量" /></div>
          </div>
          <div class="form-item">
            <div class="label">单位</div>
            <div class="field">
              <el-select v-model.number="addForm.unitId" filterable placeholder="请选择单位">
                <el-option v-for="u in units" :key="u.unitId || u.id" :value="u.unitId || u.id" :label="u.unitName || u.name" />
              </el-select>
            </div>
          </div>
          <div class="form-item">
            <div class="label">仓库</div>
            <div class="field">
              <el-select v-model.number="addForm.warehouseId" filterable placeholder="请选择仓库">
                <el-option v-for="w in warehouses" :key="w.warehouseId || w.id" :value="w.warehouseId || w.id" :label="w.warehouseName || w.name" />
              </el-select>
            </div>
          </div>
          <div class="form-item">
            <div class="label">产品数</div>
            <div class="field"><el-input v-model.number="addForm.productCount" placeholder="产品种类数量" /></div>
          </div>
          <div class="form-item">
            <div class="label">备注</div>
            <div class="field"><el-input v-model="addForm.remark" placeholder="可选" /></div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addVisible=false">取 消</el-button>
            <el-button type="primary" @click="submitAdd">提 交</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getReceiptList, addReceipt } from '@/api/warehouse/WarehouseReceipt'
import { listUnits, listWarehouses, listUsers } from '@/api/basic'
import { pageInventoryDetails } from '@/api/warehouse/InventoryDetails'
import { listProducts } from '@/api/basic'
export default {
  name: 'InboundOrder',
  data() {
    return {
      loading: false,
      query: { keyword: '', receiptType: '', pageNum: 1, pageSize: 10 },
      total: 0,
      orders: [],
      units: [],
      warehouses: [],
      users: [],
      statusMap: { 0: '待入库', 1: '部分入库', 2: '全部入库' },
      typeMap: { 0: '生产入库', 1: '采购入库', 2: '销售退货', 3: '生产退料', 4: '委外入库', 5: '其他入库' },
      addVisible: false,
      addForm: { receiptType: 0, productId: undefined, quantity: undefined, unitId: undefined, warehouseId: undefined, productCount: 1, remark: '' },
      productOptions: []
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.orders.length > 0 && this.orders.every(item => item.selected);
      },
      set(value) {
        this.orders.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.query.pageSize))
    }
  },
  created() {
    Promise.all([
      this.loadUnits(),
      this.loadWarehouses(),
      this.loadUsers()
    ]).finally(() => this.fetchList())
  },
  methods: {
    statusClass(status) {
      if (status === '待入库') return 'status-pending';
      if (status === '部分入库') return 'status-partial';
      if (status === '全部入库') return 'status-completed';
      return '';
    },
    statusLabel(v) {
      const key = v ?? '-'
      return this.statusMap[key] || '-'
    },
    typeLabel(v) {
      const key = v ?? '-'
      return this.typeMap[key] || (typeof key === 'string' && key ? key : '-')
    },
    unitName(id) {
      if (id == null) return '-'
      const u = this.units.find(x => (x.id || x.unitId) === id)
      return u ? (u.name || u.unitName) : '-'
    },
    warehouseName(id) {
      if (id == null) return '-'
      const w = this.warehouses.find(x => (x.id || x.warehouseId) === id)
      return w ? (w.name || w.warehouseName) : '-'
    },
    personName(uId) {
      if (uId == null) return '-'
      const user = this.users.find(u => (u.id || u.userId) === uId)
      return user ? (user.realName || user.real_name || user.username) : `用户${uId}`
    },
    async fetchList() {
      this.loading = true
      try {
        const params = {
          // 支持产品名称/编号模糊
          productName: (this.query.keyword || '').trim(),
          productCode: (this.query.keyword || '').trim(),
          // 兼容当前后端仅支持 receiptNo 模糊查询
          receiptNo: (this.query.keyword || '').trim(),
          receiptType: this.query.receiptType === '' ? undefined : this.query.receiptType,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize,
        }
        const res = await getReceiptList(params)
        const data = res.data?.data || {}
        const records = data.records || data.list || []
        this.total = data.total || 0
        this.orders = records.map(r => ({ selected: false, ...r }))
      } finally {
        this.loading = false
      }
    },
    async loadUnits() {
      try {
        const res = await listUnits({ pageSize: 100 })
        this.units = res.data?.data?.records || res.data?.data || res.data || []
      } catch {
        try {
          const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 300 })
          const rec = res2.data?.data?.records || []
          const map = new Map()
          rec.forEach(r => {
            if (r.unitId && r.unitName && !map.has(r.unitId)) map.set(r.unitId, r.unitName)
          })
          this.units = Array.from(map, ([unitId, unitName]) => ({ unitId, unitName }))
        } catch {
          this.units = []
        }
      }
    },
    async loadWarehouses() {
      try {
        const res = await listWarehouses({ pageSize: 100 })
        this.warehouses = res.data?.data?.records || res.data?.data || res.data || []
      } catch {
        try {
          const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 300 })
          const rec = res2.data?.data?.records || []
          const map = new Map()
          rec.forEach(r => {
            if (r.warehouseId && r.warehouseName && !map.has(r.warehouseId)) map.set(r.warehouseId, r.warehouseName)
          })
          this.warehouses = Array.from(map, ([warehouseId, warehouseName]) => ({ warehouseId, warehouseName }))
        } catch {
          this.warehouses = []
        }
      }
    },
    async loadUsers() {
      try {
        const res = await listUsers({ pageSize: 200 })
        this.users = res.data?.data?.records || res.data?.data || res.data || []
      } catch { this.users = [] }
    },
    onSearch() {
      this.query.pageNum = 1
      this.fetchList()
    },
    onReset() {
      this.query = { keyword: '', receiptType: '', pageNum: 1, pageSize: 10 }
      this.fetchList()
    },
    onPageChange(page) {
      const totalPages = Math.max(1, Math.ceil(this.total / this.query.pageSize))
      const next = Math.min(Math.max(1, page), totalPages)
      if (next === this.query.pageNum) return
      this.query.pageNum = next
      this.fetchList()
    },
    onPageSizeChange() {
      this.query.pageNum = 1
      this.fetchList()
    },
    async onAdd() {
      this.addVisible = true
      if (!this.units.length) this.loadUnits()
      if (!this.warehouses.length) this.loadWarehouses()
      if (!this.productOptions.length) this.loadProductOptions()
    },
    async submitAdd() {
      const { receiptType, productId, quantity, unitId, warehouseId, productCount, remark } = this.addForm
      if (productId == null || !quantity || !unitId || !warehouseId) {
        this.$message?.error?.('请完整填写必填项')
        return
      }
      const payload = {
        receiptType,
        productId,
        quantity,
        unitId,
        warehouseId,
        productCount,
        remark,
        // 后端必填字段兜底
        orderId: 0,
        stock: quantity,
        receiptStatus: 0,
        receiptTime: new Date(),
        // 若后端校验 uId，可在此传入当前登录用户ID；暂用 1 兜底
        uId: 1
      }
      await addReceipt(payload)
      this.$message?.success?.('新增成功')
      this.addVisible = false
      this.fetchList()
    },
    async loadProductOptions() {
      if (this.productOptions.length) return
      try {
        const res = await listProducts({ pageSize: 200 })
        const list = res.data?.data?.records || res.data?.data || res.data || []
        this.productOptions = list.map(x => ({ id: x.id || x.productId, name: x.name || x.productName }))
      } catch (e) {
        const res2 = await pageInventoryDetails({ pageNum: 1, pageSize: 300 })
        const rec = res2.data?.data?.records || []
        const map = new Map()
        rec.forEach(r => {
          if (r.productId && r.productName && !map.has(r.productId)) map.set(r.productId, r.productName)
        })
        this.productOptions = Array.from(map, ([id, name]) => ({ id, name }))
      }
    },
    formatPrice(val) {
      const num = Number(val)
      if (Number.isNaN(num)) return '-'
      return num.toFixed(2)
    },
  }
}
</script>

<style scoped>
.inbound-order-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}

.filters {
    display: flex;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-item input {
    width: 200px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-pending { color: #67c23a; }
.status-partial { color: #e6a23c; }
.status-completed { color: #909399; }

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.form-grid { display: grid; grid-template-columns: 1fr; row-gap: 12px; }
.form-item { display: grid; grid-template-columns: 96px 1fr; align-items: center; }
.form-item .label { color: #909399; }
.form-item .field :deep(.el-input), .form-item .field :deep(.el-select) { width: 100%; }
</style>
